<template>
  <div class="container">
    <!-- 头部 -->
    <div class="header">
      <el-button type="primary" @click="add" style="margin-bottom: 20px"
        >新增商品(家具)</el-button
      >
      <!-- 查询表单 -->
      <el-form :model="form_query" label-width="80px" inline>
        <el-form-item>
          <el-select
            v-model="form_query.type"
            placeholder="请选择查询条件"
            style="width: 160px; margin-right: 20px"
          >
            <el-option label="家具名称" value="name"></el-option>
            <el-option label="家具类型" value="classify"></el-option>
            <el-option label="家具材质" value="texture"></el-option>
            <el-option label="家具生产地址" value="producer"></el-option>
            <el-option label="家具风格" value="style"></el-option>
          </el-select>
          <el-form-item>
            <el-input
              v-model="form_query.value"
              placeholder="请输入查询内容"
            ></el-input>
          </el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
          <el-button type="primary" @click="resetChoose">重置</el-button>
          <el-button type="primary" @click="showAll">显示全部</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 家具列表 -->
    <el-table :data="goodsList" border style="width: 100%; margin-top: 10px">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline>
            <el-form-item
              class="every-detail"
              label="家具名称"
              :label-width="formLabelWidth_query"
            >
              <span>{{ props.row.name || "暂无" }}</span>
            </el-form-item>
            <el-form-item
              class="every-detail"
              label="家具类型"
              :label-width="formLabelWidth_query"
            >
              <span>{{ props.row.classify || "暂无" }}</span>
            </el-form-item>
            <el-form-item
              class="every-detail"
              label="家具价格(元)"
              :label-width="formLabelWidth_query"
            >
              <span>{{ props.row.price || "暂无" }}</span>
            </el-form-item>
            <el-form-item
              class="every-detail"
              label="家具重量(kg)"
              :label-width="formLabelWidth_query"
            >
              <span>{{ props.row.weight || "暂无" }}</span>
            </el-form-item>
            <el-form-item
              class="every-detail"
              label="家具材质"
              :label-width="formLabelWidth_query"
            >
              <span>{{ props.row.texture || "暂无" }}</span>
            </el-form-item>
            <el-form-item
              class="every-detail"
              label="家具生产地址"
              :label-width="formLabelWidth_query"
            >
              <span>{{ props.row.producer || "暂无" }}</span>
            </el-form-item>
            <el-form-item
              class="every-detail"
              label="家具风格"
              :label-width="formLabelWidth_query"
            >
              <span>{{ props.row.style || "暂无" }}</span>
            </el-form-item>
            <el-form-item
              class="every-detail"
              label="家具封面图片"
              :label-width="formLabelWidth_query"
            >
              <div style="display: flex">
                <div class="household_list_image">
                  <img
                    :src="imgServePath + props.row.coverImage[0]"
                    alt="家具封面图片加载错误"
                  />
                </div>
              </div>
            </el-form-item>
            <el-form-item
              class="every-detail"
              label="家具详情图片"
              :label-width="formLabelWidth_query"
            >
              <div style="display: flex; flex-wrap: wrap">
                <div
                  v-for="(item, i) in props.row.detailsImages"
                  :key="i"
                  class="household_list_image"
                >
                  <img
                    :src="imgServePath + props.row.detailsImages[i]"
                    alt="家具详情图片加载错误"
                  />
                </div>
              </div>
            </el-form-item>
            <el-form-item
              class="every-detail"
              label="家具描述"
              :label-width="formLabelWidth_query"
            >
              <span>{{ props.row.desc || "暂无" }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="家具名称" align="center" prop="name">
      </el-table-column>
      <el-table-column label="家具类型" align="center" prop="classify">
      </el-table-column>
      <el-table-column label="家具价格(元)" align="center" prop="price">
      </el-table-column>
      <!-- 操作 -->
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button @click="update(scope.row._id)" type="primary" size="mini"
            >修改
          </el-button>
          <el-button @click="del(scope.row._id)" type="danger" size="mini"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="divid_page">
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
          background
        >
        </el-pagination>
      </div>
    </div>
    <!-- 增加和修改的表单弹窗 -->
    <el-dialog
      :title="formTitle"
      :before-close="beforeClose"
      :visible.sync="dialogFormVisible"
    >
      <el-form ref="dialogFormer" :model="form" :rules="rules">
        <el-form-item
          prop="name"
          label="家具名称"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="form.name"
            autocomplete="off"
            placeholder="请输入家具名称"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="classify"
          label="家具类型"
          :label-width="formLabelWidth"
        >
          <el-select v-model="form.classify" placeholder="请选择家具类型">
            <el-option
              v-for="item in classifyOptions"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="家具价格(元)"
          prop="price"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="form.price"
            autocomplete="off"
            placeholder="请输入家具价格"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="weight"
          label="家具重量(kg)"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="form.weight"
            autocomplete="off"
            placeholder="请输入家具重量"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="texture"
          label="家具材质"
          :label-width="formLabelWidth"
        >
          <el-select v-model="form.texture" placeholder="请选择家具材质">
            <el-option
              v-for="item in textureOptions"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          prop="producer"
          label="家具生产地址"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="form.producer"
            autocomplete="off"
            placeholder="请输入家具生产地址"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="style"
          label="家具风格"
          :label-width="formLabelWidth"
        >
          <el-select v-model="form.style" placeholder="请选择家具风格">
            <el-option
              v-for="item in styleOptions"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          prop="coverImage"
          label="家具封面图片"
          :label-width="formLabelWidth"
        >
          <el-upload
            class="avatar-uploader"
            action="/img/uploadFile"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img
              v-if="imageUrlCoverImage"
              :src="imageUrlCoverImage"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="家具详情图片" :label-width="formLabelWidth">
          <el-upload
            :multiple="Multiple_detailsImages_boolean"
            class="upload_detailsImages"
            ref="upload_detailsImages"
            action="/img/uploadFile"
            list-type="picture-card"
            :on-success="Multiple_detailsImages"
            :on-preview="handlePreview_detailsImages"
            :on-remove="remove_detailsImages"
            :file-list="fileList_detailsImages"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible_detailsImages">
            <img width="100%" :src="dialogImageUrl_detailsImages" alt="" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="家具详情描述" :label-width="formLabelWidth">
          <el-input
            v-model="form.desc"
            autocomplete="off"
            placeholder="请输入家具详情描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sure">确定{{ formType }}</el-button>
        <el-button @click="cancel">取消{{ formType }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//引入辅助函数
import { mapGetters } from "vuex";
import axios from "../../utils/request.js";

export default {
  data() {
    // 家具名称验证(不能为空)
    let validateName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("名称不能为空！！！"));
      } else {
        callback();
      }
    };
    // 家具类型验证(不能为空)
    let validateClassify = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请选择类型"));
      } else {
        callback();
      }
    };
    // 家具价格验证(只能是数字,最多有两位小数)
    let priceReg = /^\d*\.{0,1}\d{0,2}$/;
    let validatePrice = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("价格不能为空！！！"));
      }
      if (!priceReg.test(value)) {
        callback(new Error("价格格式不正确(只能是数字,最多有两位小数)"));
      } else {
        callback();
      }
    };
    // 家具重量验证(只能是数字,最多有三位小数)
    let weightReg = /^\d*\.{0,1}\d{0,3}$/;
    let validateWeight = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("重量不能为空！！！"));
      }
      if (!weightReg.test(value)) {
        callback(new Error("重量格式不正确(只能是数字,最多有三位小数)"));
      } else {
        callback();
      }
    };
    // 家具材质验证(不能为空)
    let validateTexture = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请选择材质"));
      } else {
        callback();
      }
    };
    // 家具生产地址验证(不能为空)
    let validateProducer = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("生产地址不能为空！！！"));
      } else {
        callback();
      }
    };
    // 家具风格验证(不能为空)
    let validateStyle = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请选择风格"));
      } else {
        callback();
      }
    };
    // 家具封面图片验证(不能为空)
    let validateCoverImage = (rule, value, callback) => {
      if (!this.imageUrlCoverImage) {
        return callback(new Error("封面图片不能没有"));
      } else {
        callback();
      }
    };
    return {
      // 1.增加和修改的表单弹窗
      dialogFormVisible: false, //控制增加和修改的表单是否显示
      formLabelWidth: "120px", //表单的label的宽度
      formTitle: "", //表单的标题
      formType: "", //表单的类型
      //表单内容
      form: {
        name: "", // 家具名称
        classify: "", // 家具类型
        price: "", // 家具价格
        weight: "", // 家具重量
        texture: "", // 家具材质
        producer: "", // 家具生产地址
        style: "", //家具风格
        coverImage: [], //家具封面图片
        detailsImages: [], // 家具详情图片
        desc: "", // 家具描述
      },
      // 表单校验规则
      rules: {
        //
        name: [{ required: true, validator: validateName, trigger: "blur" }], // 家具名称
        classify: [
          { required: true, validator: validateClassify, trigger: "blur" },
        ], // 家具类型
        price: [{ required: true, validator: validatePrice, trigger: "blur" }], // 家具价格
        weight: [
          { required: true, validator: validateWeight, trigger: "blur" },
        ], //家具重量
        texture: [
          { required: true, validator: validateTexture, trigger: "blur" },
        ], // 家具价格
        producer: [
          { required: true, validator: validateProducer, trigger: "blur" },
        ], // 家具生产地址
        style: [{ required: true, validator: validateStyle, trigger: "blur" }], // 家具风格
        coverImage: [
          { required: true, validator: validateCoverImage, trigger: "blur" },
        ], // 家具封面图片
      },
      // 家具类型选项(卧室家具,客厅家具,餐厅家具,书房家具,卫生间家具,厨房家具,儿童房家具,户外娱乐)
      classifyOptions: [
        "卧室家具",
        "客厅家具",
        "餐厅家具",
        "书房家具",
        "卫生间家具",
        "厨房家具",
        "儿童房家具",
        "户外娱乐",
      ],
      // 家具材质选项(实木,人造板材,金属,藤编,软体)
      textureOptions: ["实木", "人造板材", "金属", "藤编", "软体"],
      // 家具风格选项(中式,欧式,美式,法式,田园式,英式,新古典,地中海风格)
      styleOptions: [
        "中式",
        "欧式",
        "美式",
        "法式",
        "英式",
        "田园式",
        "新古典",
        "地中海风格",
      ],

      //2.查询表单
      form_query: {
        type: "", //选择查询条件
        value: "", //查询内容
      },
      formLabelWidth_query: "120px", //查询表单的label的宽度

      imageUrlCoverImage: "", //家具封面图片双向绑定的路径
      imgServePath: "/img/images/", //图片服务器路径

      dialogImageUrl_detailsImages: "",
      dialogVisible_detailsImages: false,

      Multiple_detailsImages_boolean: true, //家具详情图片是否一次性传多张图片

      fileList_detailsImages: [], //存储某一条家具详情图片(修改时赋值)

      // 3.分页
      totalCount: 1, //总条数
      current: 1,
      size: 5,

      currentPage: 1,

      form_query_isTrue: false, //点击了查询按钮，改为true，点击了显示全部按钮，改为false
    };
  },
  computed: {
    ...mapGetters({
      goodsList: "goods/getGoodsListGetter", //商品列表
      shopManagerId: "goods/getShopManagerIdGetter", //门店管理员id
    }),
  },
  created() {
    this.$store
      .dispatch("goods/getGoodsListAction")
      .then((res) => (this.totalCount = res.total));
    let shopManagerId = window.localStorage.getItem("shopAdminId");
    this.$store.commit("goods/updateShopManagerIdMutation", shopManagerId);
  },
  methods: {
    //每页显示数改变
    handleSizeChange(val) {
      this.size = val;
      this.$store
        .dispatch("goods/getGoodsListAction", {
          current: this.current,
          size: this.size,
          ...this.form_query,
        })
        .then((res) => (this.totalCount = res.total));
    },
    //页码改变
    handleCurrentChange(val) {
      this.current = val;
      let obj = {};
      this.form_query_isTrue ? (obj = { ...this.form_query }) : "";
      this.$store
        .dispatch("goods/getGoodsListAction", {
          current: this.current,
          size: this.size,
          obj,
        })
        .then((res) => (this.totalCount = res.total));
    },
    //上传家具详情图片
    Multiple_detailsImages(res, file) {
      this.form.detailsImages.unshift(res.saveName);
    },
    handlePreview_detailsImages(file) {
      this.dialogImageUrl_detailsImages = file.url;
      this.dialogVisible_detailsImages = true;
    },
    // 删除单张详情图片
    remove_detailsImages(file, fileList) {
      if (this.formType === "新增") {
        this.form.detailsImages = fileList.map(
          (item) => item.response.saveName
        );
      } else if (this.formType === "修改") {
        let detailsImageName = "";
        file.response
          ? (detailsImageName = file.response.saveName)
          : (detailsImageName = file.url.substring(12));
        let i = this.form.detailsImages.indexOf(detailsImageName);
        this.form.detailsImages.splice(i, 1);
      }
    },
    //成功上传家具封面图片
    handleAvatarSuccess(res) {
      this.imageUrlCoverImage = this.imgServePath + res.saveName;
      this.form.coverImage[0] = res.saveName;
    },
    //查询
    search() {
      let obj = { ...this.form_query };
      obj.addition = true;
      this.form_query_isTrue = true;
      this.$store
        .dispatch("goods/getGoodsListAction", {
          ...obj,
          current: 1,
          size: this.size,
        })
        .then((res) => {
          this.totalCount = res.total;
        });
    },
    // 重置查询
    resetChoose() {
      this.form_query.type = "";
      this.form_query.value = "";
    },
    //显示所有
    showAll() {
      this.form_query_isTrue = false;
      this.$store
        .dispatch("goods/getGoodsListAction", {
          current: 1,
          size: this.size,
          type: "",
          value: "",
        })
        .then((res) => {
          this.totalCount = res.total;
          this.currentPage = 1;
        });
    },
    // 修改家具
    update(id) {
      this.formTitle = "修改家具信息"; //表单标题
      this.formType = "修改"; //表单类型
      this.dialogFormVisible = true; //表单是否打开
      this.$store
        .dispatch("goods/getGoodsListAction", {
          type: "_id",
          value: id,
          addition: "修改",
        })
        .then((res) => {
          this.form = res.rows[0];
          //显示家具封面图片
          this.imageUrlCoverImage =
            this.imgServePath + res.rows[0].coverImage[0];
          //显示家具详情图片
          this.fileList_detailsImages = res.rows[0].detailsImages.map(
            (item) => {
              return { url: this.imgServePath + item };
            }
          );
        });
    },
    //添加家具
    add() {
      this.formTitle = "新增家具";
      this.formType = "新增";
      this.dialogFormVisible = true;
      //清空表单
      this.form = {
        name: "", // 家具名称
        classify: "", // 家具类型
        price: "", // 家具价格
        weight: "", // 家具重量
        texture: "", // 家具材质
        producer: "", // 家具生产地址
        style: "", //家具风格
        coverImage: [], //家具封面图片
        detailsImages: [], // 家具详情图片
        desc: "", // 家具描述
      };
    },
    //表单的取消按钮
    cancel() {
      this.dialogFormVisible = false;
      this.$message({
        type: "info",
        message: "已取消" + this.formType,
      });
      //清空家具封面图片
      this.imageUrlCoverImage = "";
      //清空全部家具详情图片
      this.$refs.upload_detailsImages.clearFiles();
    },
    //表单的确定按钮
    sure() {
      this.$refs.dialogFormer.validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false;
          this.$message({
            type: "success",
            message: this.formType + "成功!",
          });
          if (this.formType === "新增") {
            this.$store
              .dispatch("goods/postGoodsListAction", {
                ...this.form,
                current: this.current,
                size: this.size,
                ...this.form_query,
              })
              .then((res) => {
                //清空家具封面图片
                this.imageUrlCoverImage = "";
                //清空全部家具详情图片
                this.$refs.upload_detailsImages.clearFiles();
                this.totalCount = res.total;
              });
          } else if (this.formType === "修改") {
            this.$store
              .dispatch("goods/putGoodsListAction", {
                ...this.form,
                current: this.current,
                size: this.size,
                ...this.form_query,
              })
              .then((res) => {
                //清空家具封面图片
                this.imageUrlCoverImage = "";
                //清空全部家具详情图片
                this.$refs.upload_detailsImages.clearFiles();
                this.totalCount = res.total;
              });
          }
        }
      });
    },
    //表单关闭前
    beforeClose(sure) {
      this.$confirm("确认关闭？", "提示", { type: "warning" })
        .then(() => {
          sure();
          this.$message({
            type: "info",
            message: "已取消" + this.formType,
          });
          //清空家具封面图片
          this.imageUrlCoverImage = "";
          //清空全部家具详情图片
          this.$refs.upload_detailsImages.clearFiles();
        })
        .catch(() => {});
    },
    //删除家具
    del(id) {
      this.$confirm("确认删除？", "提示", {
        confirmButtonText: "确定删除",
        cancelButtonText: "取消删除",
        type: "warning",
      })
        .then(() => {
          this.$store
            .dispatch("goods/deleteGoodsListAction", {
              ...this.form,
              current: this.current,
              size: this.size,
              ...this.form_query,
              id,
            })
            .then((res) => {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.totalCount = res.total;
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>

<style scoped>
.container {
  padding: 50px;
}

.every-detail {
  margin: 0;
  display: block;
}

.header {
  display: flex;
  justify-content: space-between;
}

/* 家具封面图片avatar的样式 */
.avatar-uploader {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  /* cursor: pointer; */
  overflow: hidden;
  display: flex;
  align-items: center;
  background-color: #eaeaea61;
}
.avatar-uploader:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
}
.household_list_image {
  display: flex;
  align-items: center;
  width: 100px;
  padding: 2px;
  margin: 15px 20px 15px 0;
  border: 1px dashed #409eff;
}
.household_list_image img {
  width: 100%;
}
.household_list_image:hover {
  transform: scale(2);
  z-index: 2;
  background-color: azure;
}

.divid_page {
  margin-top: 30px;
}
</style>

<style>
/* 家具详情图片样式 */
.upload_detailsImages ul {
  display: flex !important;
  flex-wrap: wrap !important;
}
.upload_detailsImages li {
  display: flex !important;
  align-items: center !important;
}
.upload_detailsImages img {
  width: 100% !important;
  height: auto !important;
}
</style>
